/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.txweb.action;

import com.jspx.boot.environment.Environment;
import com.jspx.boot.sign.CongealType;
import com.jspx.boot.sign.LanguageRes;
import com.jspx.boot.sign.UserType;
import com.jspx.boot.sign.YesNoType;
import com.jspx.sober.Transaction;
import com.jspx.sober.criteria.expression.Expression;
import com.jspx.txweb.IRole;
import com.jspx.txweb.IUserSession;
import com.jspx.txweb.annotation.HttpMethod;
import com.jspx.txweb.annotation.Operate;
import com.jspx.txweb.annotation.Safety;
import com.jspx.txweb.env.TXWeb;
import com.jspx.txweb.support.DefaultTemplateAction;
import com.jspx.txweb.table.Member;
import com.jspx.txweb.table.MemberRole;
import com.jspx.txweb.table.OperateVO;
import com.jspx.txweb.table.Role;
import com.jspx.txweb.util.TXWebUtil;
import com.jspx.txweb.view.PermissionView;
import com.jspx.utils.ArrayUtil;
import com.jspx.utils.BeanUtil;
import com.jspx.utils.StringUtil;
import com.jspx.zhex.spell.ChineseUtil;
import java.util.Collection;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: chenYuan
 * Date: 2010-11-8
 * Time: 17:50:31
 */
@HttpMethod(caption = "角色权限")
public class PermissionManageAction extends PermissionView {
    public PermissionManageAction() {

    }
    private Integer[] idArray = null;
    @Safety
    public void setIdArray(Integer[] idArray) {
        this.idArray = idArray;
    }

    @Operate(caption = "添加角色")
    public void addRole() throws Exception {
        if (isGuest()) {
            addActionMessage(language.getLang(LanguageRes.needLogin));
            setActionResult(LOGIN);
            return;
        }
        IUserSession userSession = (IUserSession) getUserSession();
        IRole userRole = userSession.getRole(permissionDAO.getNamespace());
        if (userRole == null || userRole.getUserType() < UserType.MANAGER) {

            addActionMessage(language.getLang(LanguageRes.needManagePower));
            return;
        }

        Role role = (Role) getBean(Role.class);
        role.setPutUid(userSession.getUid());
        role.setPutName(userSession.getName());
        role.setNamespace(permissionDAO.getNamespace());

        //得到简拼begin
        role.setSpelling(ChineseUtil.getFullSpell(role.getName(), ""));
        //得到简拼end

        if (permissionDAO.save(role) > 0) {
            if (role.getId()==Environment.DEBUG_ROLE_ID)
            {
                role.setId(0);
                permissionDAO.save(role);
                role.setId(Environment.DEBUG_ROLE_ID);
                permissionDAO.delete(role);
            }
            addActionMessage(language.getLang(LanguageRes.saveSuccess));
            setActionLogContent(role.getId() + ":" + role.getName());
            setActionResult(SUCCESS);
        }
    }

    @Operate(caption = "拷贝角色")
    public void copyRole() throws Exception {
        setActionResult(ROC);
        if (isGuest()) {
            addActionMessage(language.getLang(LanguageRes.needLogin));
            return;
        }
        IUserSession userSession = (IUserSession) getUserSession();
        IRole userRole = userSession.getRole(permissionDAO.getNamespace());
        if (userRole == null || userRole.getUserType() < UserType.MANAGER) {
            addActionMessage(language.getLang(LanguageRes.needManagePower));
            return;
        }

        Integer[] ids = getIntegerArray("id", idArray);
        if (ArrayUtil.isEmpty(ids)&&getId()>0) ids = new Integer[]{getId()};
        if (ArrayUtil.isEmpty(ids)) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.needSelect));
            return;
        }
        for (Integer id : ids) {
            Role role = permissionDAO.getRole(id);
            role.setId(0);
            role.setName(role.getName() + "_copy");
            role.setNamespace(permissionDAO.getNamespace());
            role.setPutUid(userSession.getUid());
            role.setPutName(userSession.getName());
            if (permissionDAO.save(role) > 0) {
                addActionMessage(language.getLang(LanguageRes.operationSuccess));
                setActionLogContent(role.getId() + ":" + role.getName());
            }
        }
    }

    @Operate(caption = "编辑角色")
    public void editRole() throws Exception {
        if (isGuest()) {
            addActionMessage(language.getLang(LanguageRes.needLogin));
            setActionResult(LOGIN);
            return;
        }
        IUserSession userSession = (IUserSession) getUserSession();
        IRole userRole = userSession.getRole(permissionDAO.getNamespace());
        if (userRole == null || userRole.getUserType() < UserType.MANAGER) {
            addActionMessage(language.getLang(LanguageRes.needManagePower));
            setActionResult(LOGIN);
            return;
        }

        Role role = (Role) getBean(Role.class);
        role.setPutUid(userSession.getUid());
        role.setPutName(userSession.getName());
        role.setNamespace(permissionDAO.getNamespace());
        //得到简拼begin
        role.setSpelling(ChineseUtil.getFullSpell(role.getName(), ""));
        //得到简拼end

        if (permissionDAO.update(role) > 0) {
            addActionMessage(language.getLang(LanguageRes.updateSuccess));
            setActionLogContent(BeanUtil.toXml(role));
            setActionResult(SUCCESS);
        }
    }

    @Operate(caption = "删除角色")
    public void delRole() throws Exception {
        setActionResult(ROC);
        if (isGuest()) {
            addActionMessage(language.getLang(LanguageRes.needLogin));
            return;
        }

        IUserSession userSession = (IUserSession) getUserSession();
        IRole userRole = userSession.getRole(permissionDAO.getNamespace());
        if (userRole == null || userRole.getUserType() < UserType.MANAGER) {
            addActionMessage(language.getLang(LanguageRes.needManagePower));
            setActionResult(LOGIN);
            return;
        }

        if (isGuest() || userSession.getRole(permissionDAO.getNamespace()).getUserType() < UserType.MANAGER) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.needManagePower) + "," + userSession.getRole(permissionDAO.getNamespace()).getUserType());
            return;
        }
        Integer[] ids = getIntegerArray("id", idArray);
        if (ArrayUtil.isEmpty(ids)&&getId()>0) ids = new Integer[]{getId()};
        if (ArrayUtil.isEmpty(ids)) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.needSelect));
            return;
        }
        if (permissionDAO.deleteRoles(ids)) {
            addActionMessage(language.getLang(LanguageRes.deleteSuccess));
            setActionLogContent(ArrayUtil.toString(ids, StringUtil.SEMICOLON));
        } else {
            addActionMessage(language.getLang(LanguageRes.deleteFailure));
        }
    }

    /**
     * 排序时间
     */
    @Operate(caption = "提前角色")
    public void sortDate() {
        setActionResult(ROC);
        if (isGuest()) {
            addActionMessage(language.getLang(LanguageRes.needLogin));
            setActionResult(LOGIN);
            return;
        }
        IUserSession userSession = (IUserSession) getUserSession();
        IRole userRole = userSession.getRole(permissionDAO.getNamespace());
        if (userRole == null || userRole.getUserType() < UserType.MANAGER) {
            addActionMessage(language.getLang(LanguageRes.needManagePower));
            setActionResult(LOGIN);
            return;
        }

        Integer[] ids = getIntegerArray("id", idArray);
        if (ArrayUtil.isEmpty(ids)&&getId()>0) ids = new Integer[]{getId()};
        if (ArrayUtil.isEmpty(ids)) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.needSelect));
            return;
        }
        if (permissionDAO.updateSortDate(ids)) {
            addActionMessage(language.getLang(LanguageRes.operationSuccess));
            setActionLogContent(ArrayUtil.toString(ids, StringUtil.SEMICOLON));
        } else {
            addActionMessage(language.getLang(LanguageRes.operationFailure));
        }
    }

    @Operate(caption = "锁定")
    public void okCongealType() {
        setActionResult(ROC);
        if (isGuest()) {
            addActionMessage(language.getLang(LanguageRes.needLogin));
            return;
        }
        IUserSession userSession = (IUserSession) getUserSession();
        IRole userRole = userSession.getRole(permissionDAO.getNamespace());
        if (userRole == null || userRole.getUserType() < UserType.MANAGER) {
            addActionMessage(language.getLang(LanguageRes.needManagePower));
            return;
        }

        Integer[] ids = getIntegerArray("id", idArray);
        if (ArrayUtil.isEmpty(ids)&&getId()>0) ids = new Integer[]{getId()};
        if (ArrayUtil.isEmpty(ids)) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.needSelect));
            return;
        }
        if (permissionDAO.updateCongealType(ids, CongealType.YES_CONGEAL)) {
            addActionMessage(language.getLang(LanguageRes.deleteSuccess));
            setActionLogContent(ArrayUtil.toString(ids, StringUtil.SEMICOLON));
        } else {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.deleteFailure));
        }
    }

    @Operate(caption = "解锁")
    public void noCongealType() {
        setActionResult(ROC);
        if (isGuest()) {
            addActionMessage(language.getLang(LanguageRes.needLogin));
            return;
        }
        IUserSession userSession = (IUserSession) getUserSession();
        IRole userRole = userSession.getRole(permissionDAO.getNamespace());
        if (userRole == null || userRole.getUserType() < UserType.MANAGER) {
            addActionMessage(language.getLang(LanguageRes.needManagePower));
            return;
        }
        Integer[] ids = getIntegerArray("id", idArray);
        if (ArrayUtil.isEmpty(ids)&&getId()>0) ids = new Integer[]{getId()};
        if (ArrayUtil.isEmpty(ids)) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.needSelect));
            return;
        }
        if (permissionDAO.updateCongealType(ids, CongealType.NO_CONGEAL)) {
            addActionMessage(language.getLang(LanguageRes.operationSuccess));
            setActionLogContent(ArrayUtil.toString(ids, StringUtil.SEMICOLON));
        } else {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.operationFailure));
        }
    }


    @Operate(caption = "设置权限")
    public void saveOperate() throws Exception {
        if (isGuest()) {
            addActionMessage(language.getLang(LanguageRes.needLogin));
            return;
        }

        IUserSession userSession = (IUserSession) getUserSession();
        IRole userRole = userSession.getRole(permissionDAO.getNamespace());
        if (userRole == null || userRole.getUserType() < UserType.MANAGER) {
            addActionMessage(language.getLang(LanguageRes.needManagePower));
            return;
        }

        Role role = permissionDAO.getRole(getId());
        if (role == null) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.needSelect));
            return;
        }

        if (!role.getNamespace().equalsIgnoreCase(permissionDAO.getNamespace())) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.invalidParameter));
            return;
        }
        role.setOperates(ArrayUtil.toString(getArray("oid", false),StringUtil.CRLF));
        if (permissionDAO.update(role, new String[]{"operates"}) > 0) {
            role = null;
            addActionMessage(language.getLang(LanguageRes.operationSuccess));
            setActionLogContent(BeanUtil.toXml(role));
        }
    }

    @SuppressWarnings("unchecked")
    @Operate(caption = "批量设置角色")
    public void memberRoles() throws Exception {
        setActionResult(ROC);
        if (isGuest()) {
            addActionMessage(language.getLang(LanguageRes.needLogin));
            return;
        }
        IUserSession userSession = (IUserSession) getUserSession();
        IRole userRole = userSession.getRole(permissionDAO.getNamespace());
        if (userRole == null || userRole.getUserType() < UserType.MANAGER) {
            addActionMessage(language.getLang(LanguageRes.needManagePower));
            return;
        }
        int roleId = getInt("roleId");
        Role role = permissionDAO.getRole(roleId);
        if (role == null) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.invalidParameter));
            return;
        }
        if (role.getUserType()> userRole.getUserType()) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.needManagePower));
            return;
        }
        Long[] uidArray = getLongArray("uid");
        Transaction transaction = permissionDAO.createTransaction();
        try {
            transaction.begin();
            for (long uid : uidArray) {
                List<MemberRole> memberRoleList = (List<MemberRole>) permissionDAO.createCriteria(MemberRole.class).add(Expression.eq("uid", uid)).add(Expression.eq("namespace", permissionDAO.getNamespace())).list(false);
                if (memberRoleList.size() == 1) {
                    //替换方式
                    MemberRole memberRole = memberRoleList.get(0);
                    memberRole.setRoleId(roleId);
                    memberRole.setUid(uid);
                    memberRole.setPutUid(userSession.getUid());
                    memberRole.setPutName(userSession.getName());
                    memberRole.setNamespace(permissionDAO.getNamespace());
                    if (permissionDAO.update(memberRole) > 0) {
                        addActionMessage(language.getLang(LanguageRes.configSuccessForEdit)+","+uid);
                    }
                } else {
                    permissionDAO.deleteAll(memberRoleList);
                    MemberRole memberRole = new MemberRole();
                    memberRole.setRoleId(roleId);
                    memberRole.setUid(uid);
                    memberRole.setPutUid(userSession.getUid());
                    memberRole.setPutName(userSession.getName());
                    memberRole.setNamespace(permissionDAO.getNamespace());
                    if (permissionDAO.save(memberRole) > 0) {
                        addActionMessage(language.getLang(LanguageRes.configSuccessForAdd)+","+uid);
                    }
                }
                memberRoleList.clear();
            }
            transaction.commit();
            setActionLogContent(ArrayUtil.toString(uidArray, StringUtil.SEMICOLON));
        } catch (Exception e) {
            transaction.rollback();
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.operationFailure));
        }
    }

    //更具默认配置分配权限
    @Operate(caption = "重置权限")
    public void reset() throws Exception {

        setActionResult(ROC);
        IUserSession userSession = (IUserSession) getUserSession();
        IRole userRole = userSession.getRole(permissionDAO.getNamespace());
        if (userRole == null || userRole.getUserType()<UserType.MANAGER) {
            addActionMessage(language.getLang(LanguageRes.needManagePower));
            return;
        }

        String[] globalOperates = null;
        String[] noneOperates = null;
        String[] userOperates = null;
        String[] manageOperates = null;
        Collection<OperateVO> operates = getOperateList();
        for (OperateVO op : operates) {
            if (op == null) continue;
            if (!op.getNamespace().contains("/"))
            {
                userOperates = ArrayUtil.add(userOperates, op.getActionMethodId());
                if (TXWebUtil.defaultExecute.equals(op.getClassMethod()) || "login".equalsIgnoreCase(op.getClassMethod())
                        || "exit".equalsIgnoreCase(op.getClassMethod())
                        || DefaultTemplateAction.class.getName().equalsIgnoreCase(op.getClassName())
                        || op.getNamespace().endsWith("validator")||
                        op.getNamespace().endsWith("juweb/picture")||op.getNamespace().endsWith("juweb/download")||op.getNamespace().endsWith("jcms/download"))

                    noneOperates = ArrayUtil.add(noneOperates, op.getActionMethodId());
            }
            if (!op.getNamespace().contains("jcms/htdoc"))
            {
                userOperates = ArrayUtil.add(userOperates, op.getActionMethodId());
            }
            if (!op.getNamespace().contains("/validator"))
            {
                userOperates = ArrayUtil.add(userOperates, op.getActionMethodId());
            }
            if (!op.getNamespace().contains("/help"))
            {
                userOperates = ArrayUtil.add(userOperates, op.getActionMethodId());
            }

            if (TXWeb.global.equalsIgnoreCase(op.getNamespace())|| "*".equals(op.getActionName()))
            {
                globalOperates = ArrayUtil.add(globalOperates, op.getActionMethodId());
                noneOperates = ArrayUtil.add(noneOperates, op.getActionMethodId());
            }
            manageOperates = ArrayUtil.add(manageOperates, op.getActionMethodId());
        }

        List<Role> roles = permissionDAO.getRoleList();
        if (!roles.isEmpty()) {
            for (Role role : roles) {
                if (role.getUserType() == UserType.NONE)
                {
                    ArrayUtil.sort(noneOperates, "/", true);
                    role.setOperates(ArrayUtil.toString(noneOperates,StringUtil.CRLF));
                }
                else if (role.getUserType() < UserType.MANAGER)
                {
                    ArrayUtil.sort(userOperates, "/", true);
                    role.setOperates(ArrayUtil.toString(userOperates, StringUtil.CRLF));
                }
                else {
                    ArrayUtil.sort(manageOperates, "/", true);
                    role.setOperates(ArrayUtil.toString(manageOperates, StringUtil.CRLF));
                }
                permissionDAO.update(role, new String[]{"operates"});
            }
            roles.clear();
            addActionMessage(language.getLang(LanguageRes.powerResetSuccess));
        } else {

            Role role = new Role();
            role.setUserType(UserType.NONE);
            ArrayUtil.sort(noneOperates, "/", true);
            role.setOperates(ArrayUtil.toString(noneOperates, StringUtil.CRLF));
            role.setImages("/share/pimg/usertype/0001.gif");
            role.setName("游客");
            //得到简拼begin
            role.setSpelling(ChineseUtil.getFullSpell(role.getName(), ""));
            //得到简拼end
            role.setUseUpload(YesNoType.NO);
            role.setNamespace(permissionDAO.getNamespace());
            permissionDAO.save(role);

            role = new Role();
            role.setUserType(UserType.USER);
            role.setImages("/share/pimg/usertype/0002.gif");
            ArrayUtil.sort(userOperates, "/", true);
            role.setOperates(ArrayUtil.toString(userOperates, StringUtil.CRLF));
            role.setName("会员");
            //得到简拼begin
            role.setSpelling(ChineseUtil.getFullSpell(role.getName(), ""));
            //得到简拼end
            role.setUseUpload(YesNoType.YES);
            role.setUploadFileTypes("pdf;doc;docx;ppt;pptx;xls;xlsx;rar;zip;7z;rtf;wps;mht;ett;jpg;png;gif;bmp;swf;avi;flv;txt;mp3;mp4;mkv;one;tiff;gd;hlp;chm");
            role.setNamespace(permissionDAO.getNamespace());
            permissionDAO.save(role);


            role = new Role();
            role.setUserType(UserType.INTENDANT);
            ArrayUtil.sort(manageOperates, "/", true);
            role.setOperates(ArrayUtil.toString(manageOperates, StringUtil.CRLF));
            role.setImages("/share/pimg/usertype/0005.gif");
            role.setName("操作人员");
            //得到简拼begin
            role.setSpelling(ChineseUtil.getFullSpell(role.getName(), ""));
            //得到简拼end
            role.setUseUpload(YesNoType.YES);
            role.setUploadFileTypes("*");
            role.setNamespace(permissionDAO.getNamespace());
            permissionDAO.save(role);
            addActionMessage(language.getLang(LanguageRes.operationSuccess));


            role = new Role();
            role.setUserType(UserType.MANAGER);
            ArrayUtil.sort(manageOperates, "/", true);
            role.setOperates(ArrayUtil.toString(manageOperates, StringUtil.CRLF));
            role.setImages("/share/pimg/usertype/0006.gif");
            role.setName("管理员");
            //得到简拼begin
            role.setSpelling(ChineseUtil.getFullSpell(role.getName(), ""));
            //得到简拼end
            role.setUseUpload(YesNoType.YES);
            role.setUploadFileTypes("*");
            role.setNamespace(permissionDAO.getNamespace());
            permissionDAO.save(role);
            addActionMessage(language.getLang(LanguageRes.operationSuccess));
        }
    }

    public String execute() throws Exception {
        if (isMethodInvoked()) {
            permissionDAO.evict(MemberRole.class);
            permissionDAO.evict(Role.class);
            permissionDAO.evict(Member.class);
        }
        return super.execute();
    }
}